//
//  DTHomeApi.swift
//  Architecture
//
//  Created by tianXin on 2017/9/13.
//  Copyright © 2017年 田鑫. All rights reserved.
//

import Foundation
import Moya
import SwiftyJSON

let HomeProvider = MoyaProvider<DTHomeRequest>(plugins: [NetworkLoggerPlugin(verbose: true, responseDataFormatter: JSONResponseDataFormatter)])

public enum DTHomeRequest {
    case timeLine
    case timeList(pageIndex: Int,pageSize: Int)
}
extension DTHomeRequest: TargetType {
    public var baseURL: URL { return URL(string: BASE_URL)! }
    public var path: String {
      switch self {
      case .timeLine:
        return API_URL+ARTICLE_LIST
      case .timeList(_ , _):
        return API_URL+ARTICLE_LIST
      }
    }
    public var method: Moya.Method {
      return .get
    }
    public var parameters: [String: Any]? {
      switch self {
      case .timeLine:
        return ["table":"news","classid":"0","query":"isgood","pageSize":3]
      case .timeList(let pageIndex, let pageSize):
        return ["table":"news","classid":"0","pageIndex":pageIndex,"pageSize":pageSize]
      }
    }
    public var parameterEncoding: ParameterEncoding {
      return URLEncoding.default
    }
    public var task: Task {
      return .request
    }
    public var validate: Bool {
      switch self {
      case .timeLine:
        return true
      default:
        return false
      }
    }
    public var sampleData: Data {
      switch self {
      case .timeLine:
        return "Half measures are as bad as nothing at all.".data(using: String.Encoding.utf8)!
      case .timeList(let pageIndex, let pageSize):
        return "{\"pageIndex\": \"\(pageIndex)\", \"pageSize\": \(pageSize)}".data(using: String.Encoding.utf8)!
      }
    }
    public var headers: [String: String]? {
      return nil
    }
  }

  //MARK: - Response Handlers

  extension Moya.Response {
    func mapNSArray() throws -> NSArray {
      guard let dict = try self.mapJSON() as? NSDictionary ,let array = dict["data"] as? NSArray else {
        throw MoyaError.jsonMapping(self)
      }
      return array
    }
  }

  // MARK: - Provider setup

  private func JSONResponseDataFormatter(_ data: Data) -> Data {
    do {
      let dataAsJSON = try JSONSerialization.jsonObject(with: data)
      let prettyData =  try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted)
      return prettyData
    } catch {
      return data // fallback to original data if it can't be serialized.
    }
}

// MARK: - Provider support

private extension String {
    var urlEscaped: String {
      return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
    }
}
